package com.example.restaurantclient.Activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.example.restaurantclient.ConfigUtil.ConfigUtil;
import com.example.restaurantclient.Entities.Member;
import com.example.restaurantclient.R;
import com.google.gson.Gson;
import com.mob.MobSDK;
import com.zhenzi.sms.ZhenziSmsClient;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
import okhttp3.OkHttpClient;

public class RegisterActivity extends AppCompatActivity {

    private OkHttpClient okHttpClient;
    private String code;

    private EditText etPhone;
    private EditText etCode;
    private Button btnRequestCode;//获取验证码按钮
    private Button btnRegister;
    private EditText etName;
    private EditText etPwd;

    private String phone;
    private String result;

    private static final int REQUEST_PERMISSION_CODE = 0;

    //短信验证码
    private ZhenziSmsClient client;

    int i = 30;//倒计时

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        //设置透明度
        RelativeLayout layout = findViewById(R.id.register_bg);
        layout.getBackground().setAlpha(150);
        //初始化控件
        initView();
        btnRequestCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                phone = etPhone.getText().toString();
                Log.e("phone", "222222222 :" + phone);
                // 1. 通过规则判断手机号
                if (judgePhoneNums(phone)) {
                    // 2. 通过sdk发送短信验证
                    SMSSDK.getVerificationCode("86", phone);
                    btnRequestCode.setClickable(false);
                    btnRequestCode.setText("重新发送(" + i + ")");
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            for (; i > 0; i--) {
                                handler.sendEmptyMessage(-9);
                                if (i < 0) {
                                    break;
                                }
                                try {
                                    Thread.sleep(1000);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                            }
                            handler.sendEmptyMessage(-8);

                        }
                    }).start();
                }

            }
        });
        //申请权限
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_SMS)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_SMS}, REQUEST_PERMISSION_CODE);
        }


        btnRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (judCord()) {
                    code = etCode.getText().toString();
                    SMSSDK.submitVerificationCode("86", phone, code);
                }
            }
        });

    }

    private void initView() {
        okHttpClient = new OkHttpClient();
        etCode = findViewById(R.id.input_code_et);
        etPhone = findViewById(R.id.input_phone_et);
        etName = findViewById(R.id.input_name_et);
        etPwd = findViewById(R.id.input_password_et);
        btnRequestCode = findViewById(R.id.request_code_btn);
        btnRegister = findViewById(R.id.login_commit_btn);

        /*client=new ZhenziSmsClient("https://sms_developer.zhenzikj.com",
                "110827","8559cc82-e523-4b20-b389-91c2aaf19820");*/

        // 启动短信验证sdk
        MobSDK.init(this, "35326b754a64f", "7124739edc5827a621ab81c49f8856be");
        /**
         * 短信SDK回调
         * @param event    事件code
         * @param result   结果code
         * @param data     回调的数据对象
         */
        EventHandler eventHandler = new EventHandler() {
            @Override
            public void afterEvent(int event, int result, Object data) {
                Message msg = new Message();
                msg.arg1 = event;
                msg.arg2 = result;
                msg.obj = data;
                handler.sendMessage(msg);
            }
        };
        //注册回调监听接口
        SMSSDK.registerEventHandler(eventHandler);
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            if (msg.what == -9) {
                btnRequestCode.setText("重新发送(" + i + ")");
            } else if (msg.what == -8) {
                btnRequestCode.setText("获取验证码");
                btnRequestCode.setClickable(true);
                i = 30;
            } else {
                int event = msg.arg1;
                int result = msg.arg2;
                Object data = msg.obj;
                if (result == SMSSDK.RESULT_COMPLETE) {
                    if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                        Toast.makeText(getApplicationContext(), "成功获取验证码",
                                Toast.LENGTH_SHORT).show();
                    } else if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                        Toast.makeText(getApplicationContext(), "注册成功",
                                Toast.LENGTH_SHORT).show();
                        String name = etName.getText().toString();
                        String pwd = etPwd.getText().toString();

                        Intent intent = new Intent(RegisterActivity.this,
                                LoginActivity.class);
                        intent.putExtra("Register", "注册成功");
                        intent.putExtra("phone", phone);
                        intent.putExtra("name", name);
                        intent.putExtra("pwd", pwd);
                        //新用户注册
                        Member member = new Member();
                        member.setMemberPwd(pwd);
                        member.setMemberPhone(phone);
                        member.setMemberName(name);
                        // InsertMember(member);
                        startActivity(intent);
                    } else {
                        ((Throwable) data).printStackTrace();
                    }
                }
            }

        }
    };

    //判断手机号码
    private boolean judgePhoneNums(String phoneNums) {
        if (isMatchLength(phoneNums, 11)
                && isMobileNO(phoneNums)) {
            return true;
        } else {
            Toast.makeText(this, "手机号码输入有误！", Toast.LENGTH_SHORT).show();
            return false;
        }

    }

    public static boolean isMatchLength(String str, int length) {
        if (str.isEmpty()) {
            return false;
        } else {
            return str.length() == length ? true : false;
        }
    }

    public static boolean isMobileNO(String mobileNums) {
        /*
         * 移动：134、135、136、137、138、139、150、151、157(TD)、158、159、187、188
         * 联通：130、131、132、152、155、156、185、186 电信：133、153、180、189、（1349卫通）
         * 总结起来就是第一位必定为1，第二位必定为3或5或8，其他位置的可以为0-9
         */
        String telRegex = "[1][358]\\d{9}";// "[1]"代表第1位为数字1，"[358]"代表第二位可以为3、5、8中的一个，"\\d{9}"代表后面是可以是0～9的数字，有9位。
        if (TextUtils.isEmpty(mobileNums))
            return false;
        else
            return mobileNums.matches(telRegex);
    }

    //新用户注册
    private void InsertMember(final Member member) {
        new Thread() {
            @Override
            public void run() {
                super.run();
                try {
                    URL url = new URL(ConfigUtil.SERVER_ADDR + "LoginMember");
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    //设置请求方式
                    connection.setRequestMethod("POST");
                    OutputStream outputStream = connection.getOutputStream();
                    InputStream inputStream = connection.getInputStream();
                    Gson gson = new Gson();
                    outputStream.write(gson.toJson(member).getBytes());
                    byte[] buffer = new byte[256];
                    int len = inputStream.read(buffer);
                    String content = new String(buffer, 0, len);
                    inputStream.close();
                    outputStream.close();
                    if (content.equals("true")) {
                        Log.e("insert", "插入成功");
                    }

                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    private boolean judCord() {
        if (TextUtils.isEmpty(etCode.getText().toString().trim())) {
            Toast.makeText(RegisterActivity.this, "请输入验证码", Toast.LENGTH_LONG).show();
            etCode.requestFocus();
            return false;
        } else if (etCode.getText().toString().trim().length() != 6) {
            Toast.makeText(RegisterActivity.this, "您的验证码位数不正确", Toast.LENGTH_LONG).show();
            etCode.requestFocus();
            return false;
        } else {
            code = etCode.getText().toString().trim();
            return true;
        }
    }


    /**
     * 从字符串中截取连续6位数字组合 ([0-9]{6})截取六位数字 进行前后断言不能出现数字 用于从短信中获取动态密码
     *
     * @param content 短信内容
     * @return 截取得到的6位动态密码
     */
    public String getDynamicPwd(String content) {
        // 此正则表达式验证六位数字的短信验证码
        Pattern pattern = Pattern.compile("(?<![0-9])([0-9]{6})(?![0-9])");
        Matcher matcher = pattern.matcher(content);
        String dynamicPwd = "";
        if (matcher.find()) {
            dynamicPwd = matcher.group(0);
            Log.i("TAG", "getDynamicPwd: find pwd=" + dynamicPwd);
        } else {
            dynamicPwd = "";
            Toast.makeText(this, "未检测到验证码", Toast.LENGTH_SHORT).show();
        }
        return dynamicPwd;
    }

    @Override
    protected void onDestroy() {
        SMSSDK.unregisterAllEventHandler();
        super.onDestroy();
    }


}